package cn.wolfcode.shop.cloud.resolver;

import cn.wolfcode.shop.cloud.domain.User;
import cn.wolfcode.shop.cloud.redis.RedisService;
import cn.wolfcode.shop.cloud.util.CookieUtil;
import cn.wolfcode.shop.cloud.util.MemberKeyPrefixUtil;
import cn.wolfcode.shop.cloud.util.UserValidAnno;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private RedisService redisService;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {

        return methodParameter.getParameterType()== User.class && methodParameter.getParameterAnnotation(UserValidAnno.class)!=null;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        String userToken = CookieUtil.getCookieValue(request, "userToken");
        User user = redisService.get(MemberKeyPrefixUtil.USER_TOKEN, userToken, User.class);
        return user;
    }
}
